/*
 * Copyright (c) 2024 Black Sesame Technologies
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "dal_cyclonedds/listener_impl/DomainParticipantListenerImpl.hpp"
#include "dal_cyclonedds/entity_impl/DalTopicImpl.hpp"
#include "dal_cyclonedds/entity_impl/DalDataWriterImpl.hpp"
#include "dal_cyclonedds/entity_impl/DalDataReaderImpl.hpp"
#include "dal_cyclonedds/entity_impl/DalSubscriberImpl.hpp"
#include "dal_cyclonedds/utils/log.hpp"

static void on_inconsistent_topic_participant(dds_entity_t topic,
    const dds_inconsistent_topic_status_t status, void* arg)
{
    dal_domain_participant_listener_callbacks_t *callbacks_
        = reinterpret_cast<dal_domain_participant_listener_callbacks_t*>(arg);
    if (callbacks_->on_inconsistent_topic == nullptr)
        return;

    dal_topic_t dal_topic;
    dal_inconsistent_topic_status_t dal_status;
    DalTopicImpl* topic_impl = new DalTopicImpl(topic, nullptr);
    if (!topic_impl) {
        LOG_ERROR() << "DalTopicImpl memory allocation failed." << LOG_ENDL;
        return;
    }
    dal_topic.handle_ = topic_impl;
    StatusConverter::GetInstance()->ConvertInconsistentTopicStatusFromCycloneddsToDal(&status,
                                                                                   &dal_status);

    void* data = callbacks_->data_;
    (callbacks_->on_inconsistent_topic)(&dal_topic, &dal_status, data);
    delete topic_impl;
}

static void on_liveliness_lost_participant(dds_entity_t writer,
    const dds_liveliness_lost_status_t status, void* arg)
{
    dal_domain_participant_listener_callbacks_t *callbacks_
        = reinterpret_cast<dal_domain_participant_listener_callbacks_t*>(arg);
    if (callbacks_->on_liveliness_lost == nullptr)
        return;

    dal_datawriter_t dal_writer;
    dal_liveliness_lost_status_t dal_status;
    DalDataWriterImpl* writer_impl = new DalDataWriterImpl(writer, nullptr);
    if (!writer_impl) {
        LOG_ERROR() << "DalDataWriterImpl memory allocation failed." << LOG_ENDL;
        return;
    }
    dal_writer.handle_ = writer_impl;
    StatusConverter::GetInstance()->ConvertLivelinessLostStatusFromCycloneddsToDal(&status,
                                                                                &dal_status);

    void* data = callbacks_->data_;
    (callbacks_->on_liveliness_lost)(&dal_writer, &dal_status, data);
    delete writer_impl;
}

static void on_offered_deadline_missed_participant(dds_entity_t writer,
    const dds_offered_deadline_missed_status_t status, void* arg)
{
    dal_domain_participant_listener_callbacks_t *callbacks_
        = reinterpret_cast<dal_domain_participant_listener_callbacks_t*>(arg);
    if (callbacks_->on_offered_deadline_missed == nullptr)
        return;

    dal_datawriter_t dal_writer;
    dal_offered_deadline_missed_status_t dal_status;
    DalDataWriterImpl* writer_impl = new DalDataWriterImpl(writer, nullptr);
    if (!writer_impl) {
        LOG_ERROR() << "DalDataWriterImpl memory allocation failed." << LOG_ENDL;
        return;
    }
    dal_writer.handle_ = writer_impl;
    StatusConverter::GetInstance()->ConvertOfferedDeadlineMissedStatusFromCycloneddsToDal(&status,
                                                                                       &dal_status);

    void* data = callbacks_->data_;
    (callbacks_->on_offered_deadline_missed)(&dal_writer, &dal_status, data);
    delete writer_impl;
}

static void on_offered_incompatible_qos_participant(dds_entity_t writer,
    const dds_offered_incompatible_qos_status_t status, void* arg)
{
    dal_domain_participant_listener_callbacks_t *callbacks_
        = reinterpret_cast<dal_domain_participant_listener_callbacks_t*>(arg);
    if (callbacks_->on_offered_incompatible_qos == nullptr)
        return;

    dal_datawriter_t dal_writer;
    dal_offered_incompatible_qos_status_t dal_status;
    DalDataWriterImpl* writer_impl = new DalDataWriterImpl(writer, nullptr);
    if (!writer_impl) {
        LOG_ERROR() << "DalDataWriterImpl memory allocation failed." << LOG_ENDL;
        return;
    }
    dal_writer.handle_ = writer_impl;
    StatusConverter::GetInstance()->ConvertOfferedIncompatibleQosStatusFromCycloneddsToDal(
        &status, &dal_status);
    void* data = callbacks_->data_;
    (callbacks_->on_offered_incompatible_qos)(&dal_writer, &dal_status, data);
    delete writer_impl;
}

static void on_data_on_readers_participant(dds_entity_t subscriber, void* arg)
{
    dal_domain_participant_listener_callbacks_t *callbacks_
        = reinterpret_cast<dal_domain_participant_listener_callbacks_t*>(arg);
    if (callbacks_->on_data_on_readers == nullptr)
        return;

    dal_subscriber_t dal_sub;
    DalSubscriberImpl* sub_impl = new DalSubscriberImpl(subscriber, nullptr);
    if (!sub_impl) {
        LOG_ERROR() << "DalSubscriberImpl memory allocation failed." << LOG_ENDL;
        return;
    }
    dal_sub.handle_ = sub_impl;
    void* data = callbacks_->data_;
    (callbacks_->on_data_on_readers)(&dal_sub, data);
    delete sub_impl;
}

static void on_sample_lost_participant(dds_entity_t reader,
    const dds_sample_lost_status_t status, void* arg)
{
    dal_domain_participant_listener_callbacks_t *callbacks_
        = reinterpret_cast<dal_domain_participant_listener_callbacks_t*>(arg);
    if (callbacks_->on_sample_lost == nullptr)
        return;

    dal_datareader_t dal_reader;
    dal_sample_lost_status_t dal_status;
    DalDataReaderImpl* reader_impl = new DalDataReaderImpl(reader, nullptr);
    if (!reader_impl) {
        LOG_ERROR() << "DalDataReaderImpl memory allocation failed." << LOG_ENDL;
        return;
    }
    dal_reader.handle_ = reader_impl;
    StatusConverter::GetInstance()->ConvertSampleLostStatusFromCycloneddsToDal(&status, &dal_status);

    void* data = callbacks_->data_;
    (callbacks_->on_sample_lost)(&dal_reader, &dal_status, data);
    delete reader_impl;
}

static void on_data_available_participant(dds_entity_t reader, void* arg)
{
    dal_domain_participant_listener_callbacks_t *callbacks_
        = reinterpret_cast<dal_domain_participant_listener_callbacks_t*>(arg);
    if (callbacks_->on_data_available == nullptr)
        return;

    dal_datareader_t dal_reader;
    DalDataReaderImpl* reader_impl = new DalDataReaderImpl(reader, nullptr);
    if (!reader_impl) {
        LOG_ERROR() << "DalDataReaderImpl memory allocation failed." << LOG_ENDL;
        return;
    }
    dal_reader.handle_ = reader_impl;

    void* data = callbacks_->data_;
    (callbacks_->on_data_available)(&dal_reader, data);
    delete reader_impl;
}

static void on_sample_rejected_participant(dds_entity_t reader,
    const dds_sample_rejected_status_t status, void* arg)
{
    dal_domain_participant_listener_callbacks_t *callbacks_
        = reinterpret_cast<dal_domain_participant_listener_callbacks_t*>(arg);
    if (callbacks_->on_sample_rejected == nullptr)
        return;

    dal_datareader_t dal_reader;
    dal_sample_rejected_status_t dal_status;
    DalDataReaderImpl* reader_impl = new DalDataReaderImpl(reader, nullptr);
    if (!reader_impl) {
        LOG_ERROR() << "DalDataReaderImpl memory allocation failed." << LOG_ENDL;
        return;
    }
    dal_reader.handle_ = reader_impl;
    StatusConverter::GetInstance()->ConvertSampleRejectedStatusFromCycloneddsToDal(&status,
                                                                                &dal_status);

    void* data = callbacks_->data_;
    (callbacks_->on_sample_rejected)(&dal_reader, &dal_status, data);
    delete reader_impl;
}

static void on_liveliness_changed_participant(dds_entity_t reader,
    const dds_liveliness_changed_status_t status, void* arg)
{
    dal_domain_participant_listener_callbacks_t *callbacks_
        = reinterpret_cast<dal_domain_participant_listener_callbacks_t*>(arg);
    if (callbacks_->on_liveliness_changed == nullptr)
        return;

    dal_datareader_t dal_reader;
    dal_liveliness_changed_status_t dal_status;
    DalDataReaderImpl* reader_impl = new DalDataReaderImpl(reader, nullptr);
    if (!reader_impl) {
        LOG_ERROR() << "DalDataReaderImpl memory allocation failed." << LOG_ENDL;
        return;
    }
    dal_reader.handle_ = reader_impl;
    StatusConverter::GetInstance()->ConvertLivelinessChangedStatusFromCycloneddsToDal(&status,
                                                                                   &dal_status);

    void* data = callbacks_->data_;
    (callbacks_->on_liveliness_changed)(&dal_reader, &dal_status, data);
    delete reader_impl;
}

static void on_requested_deadline_missed_participant(dds_entity_t reader,
    const dds_requested_deadline_missed_status_t status, void* arg)
{
    dal_domain_participant_listener_callbacks_t *callbacks_
        = reinterpret_cast<dal_domain_participant_listener_callbacks_t*>(arg);
    if (callbacks_->on_requested_deadline_missed == nullptr)
        return;

    dal_datareader_t dal_reader;
    dal_requested_deadline_missed_status_t dal_status;
    DalDataReaderImpl* reader_impl = new DalDataReaderImpl(reader, nullptr);
    if (!reader_impl) {
        LOG_ERROR() << "DalDataReaderImpl memory allocation failed." << LOG_ENDL;
        return;
    }
    dal_reader.handle_ = reader_impl;
    StatusConverter::GetInstance()->ConvertRequestedDeadlineMissedStatusFromCycloneddsToDal(
        &status, &dal_status);

    void* data = callbacks_->data_;
    (callbacks_->on_requested_deadline_missed)(&dal_reader, &dal_status, data);
    delete reader_impl;
}

static void on_requested_incompatible_qos_participant(dds_entity_t reader,
    const dds_requested_incompatible_qos_status_t status, void* arg)
{
    dal_domain_participant_listener_callbacks_t *callbacks_
        = reinterpret_cast<dal_domain_participant_listener_callbacks_t*>(arg);
    if (callbacks_->on_requested_incompatible_qos == nullptr)
        return;

    dal_datareader_t dal_reader;
    dal_requested_incompatible_qos_status_t dal_status;
    DalDataReaderImpl* reader_impl = new DalDataReaderImpl(reader, nullptr);
    if (!reader_impl) {
        LOG_ERROR() << "DalDataReaderImpl memory allocation failed." << LOG_ENDL;
        return;
    }
    dal_reader.handle_ = reader_impl;
    StatusConverter::GetInstance()->ConvertRequestedIncompatibleQosStatusFromCycloneddsToDal(
        &status, &dal_status);

    void* data = callbacks_->data_;
    (callbacks_->on_requested_incompatible_qos)(&dal_reader, &dal_status, data);
    delete reader_impl;
}

static void on_publication_matched_participant(dds_entity_t writer,
    const dds_publication_matched_status_t status, void* arg)
{
    dal_domain_participant_listener_callbacks_t *callbacks_
        = reinterpret_cast<dal_domain_participant_listener_callbacks_t*>(arg);
    if (callbacks_->on_publication_matched == nullptr)
        return;

    dal_datawriter_t dal_writer;
    dal_publication_matched_status_t dal_status;
    DalDataWriterImpl* writer_impl = new DalDataWriterImpl(writer, nullptr);
    if (!writer_impl) {
        LOG_ERROR() << "DalDataWriterImpl memory allocation failed." << LOG_ENDL;
        return;
    }
    dal_writer.handle_ = writer_impl;
    StatusConverter::GetInstance()->ConvertPublicationMatchedStatusFromCycloneddsToDal(&status,
                                                                                    &dal_status);

    void* data = callbacks_->data_;
    (callbacks_->on_publication_matched)(&dal_writer, &dal_status, data);
    delete writer_impl;
}

static void on_subscription_matched_participant(dds_entity_t reader,
    const dds_subscription_matched_status_t  status, void* arg)
{
    dal_domain_participant_listener_callbacks_t *callbacks_
        = reinterpret_cast<dal_domain_participant_listener_callbacks_t*>(arg);
    if (callbacks_->on_subscription_matched == nullptr)
        return;

    dal_datareader_t dal_reader;
    dal_subscription_matched_status_t dal_status;
    DalDataReaderImpl* reader_impl = new DalDataReaderImpl(reader, nullptr);
    if (!reader_impl) {
        LOG_ERROR() << "DalDataReaderImpl memory allocation failed." << LOG_ENDL;
        return;
    }
    dal_reader.handle_ = reader_impl;
    StatusConverter::GetInstance()->ConvertSubscriptionMatchedStatusFromCycloneddsToDal(&status,
                                                                                     &dal_status);

    void* data = callbacks_->data_;
    (callbacks_->on_subscription_matched)(&dal_reader, &dal_status, data);
    delete reader_impl;
}

static void on_participant_discovery(dds_entity_t participant, void* info)
{
    // dds_entity_t waitset = dds_create_waitset(DDS_CYCLONEDDS_HANDLE);
    // if (waitset < 0) {
    //     LOG_ERROR() << "DalDataReaderImpl failed to create waitset." << LOG_ENDL;
    //     return;
    // }

    // sd_participant_ = dds_create_reader(this->ppant, DDS_BUILTIN_TOPIC_DCPSPARTICIPANT, nullptr, nullptr);
    // if (sd_participant_) {
    //     LOG_ERROR() << "DalDataReaderImpl create cyclone DCPSParticipant reader failed." << LOG_ENDL;
    //     return;
    // }

    // if (dds_set_status_mask(sd_participant_, DDS_DATA_AVAILABLE_STATUS) < 0) {
    //     LOG_ERROR() << "DalDataReaderImpl set status mask of cyclone DCPSParticipant reader failed." << LOG_ENDL;
    //     return;
    // }

    // if (dds_waitset_attach(waitset, sd_participant_, 0) < 0) {
    //     LOG_ERROR() << "DalDataReaderImpl failed to attach entities to waitset." << LOG_ENDL;
    //     delete(waitset);
    //     return;
    // }
}


DomainParticipantListenerImpl::DomainParticipantListenerImpl(
    dal_domain_participant_listener_callbacks_t callbacks)
{
    callbacks_ = callbacks;
    participant_monitor_callback_ = nullptr;
}

DomainParticipantListenerImpl::~DomainParticipantListenerImpl()
{
    // c_listener release while releasing participant.
}

void DomainParticipantListenerImpl::set_participant_monitor_callback(
    dal_participant_monitor_callback callback)
{
    this->participant_monitor_callback_ = callback;
}

void DomainParticipantListenerImpl::set_participant_monitor_callback_data(void* data)
{
    this->participant_monitor_callback_data_ = data;
}

dal_participant_monitor_callback DomainParticipantListenerImpl::get_participant_monitor_callback()
{
    return this->participant_monitor_callback_;
}

void* DomainParticipantListenerImpl::get_participant_monitor_callback_data()
{
    return this->participant_monitor_callback_data_;
}

dds_listener_t* DomainParticipantListenerImpl::CycloneDDSListener()
{
    if (c_listener_ == nullptr) {
        c_listener_ = dds_create_listener(NULL);
    }
    dds_lset_inconsistent_topic_arg(c_listener_, on_inconsistent_topic_participant, &callbacks_, true);
    dds_lset_liveliness_lost_arg(c_listener_, on_liveliness_lost_participant, &callbacks_, true);
    dds_lset_offered_deadline_missed_arg(c_listener_, on_offered_deadline_missed_participant, &callbacks_, true);
    dds_lset_offered_incompatible_qos_arg(c_listener_, on_offered_incompatible_qos_participant, &callbacks_, true);
    // dds_lset_data_on_readers_arg(c_listener_, on_data_on_readers_participant, &callbacks_, true);

    dds_lset_sample_lost_arg(c_listener_, on_sample_lost_participant, &callbacks_, true);
    dds_lset_data_available_arg(c_listener_, on_data_available_participant, &callbacks_, true);
    dds_lset_sample_rejected_arg(c_listener_, on_sample_rejected_participant, &callbacks_, true);
    dds_lset_liveliness_changed_arg(c_listener_, on_liveliness_changed_participant, &callbacks_, true);
    dds_lset_requested_deadline_missed_arg(c_listener_, on_requested_deadline_missed_participant, &callbacks_, true);
    dds_lset_requested_incompatible_qos_arg(c_listener_, on_requested_incompatible_qos_participant, &callbacks_, true);
    dds_lset_publication_matched_arg(c_listener_, on_publication_matched_participant, &callbacks_, true);
    dds_lset_subscription_matched_arg(c_listener_, on_subscription_matched_participant, &callbacks_, true);

    return c_listener_;
}
